package esiag.pds.jms;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.spring.ActiveMQConnectionFactory;

import esiag.pds.beans.Information;
import esiag.psd.cacheManager.CacheManager;

public class Sender {

	private  String URL="";
	private  String QUEUE;
	private CacheManager cm;
	private ObjectMessage msg;
	private MessageProducer producer ;
	
	public Sender(CacheManager cm, String queue,String url) {
		// TODO Auto-generated constructor stub
		this.cm=cm;
		QUEUE=queue;
		this.URL=url;
		
		try{
			ConnectionFactory factory = new org.apache.activemq.ActiveMQConnectionFactory(URL);
			Connection connection = factory.createConnection();
			connection.start();
			
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			Destination destination = session.createQueue(QUEUE);
			
			producer= session.createProducer(destination);
			
			msg = session.createObjectMessage();
			}
		catch(Exception e){	
		}
	}
	
	public void send(Information info) {
		try{
			msg.setObject(info);
			producer.send(msg);
			System.out.println("Informations sent..=====>");	
		}
		catch(JMSException ex){
			ex.printStackTrace();
		}	
	}
	
	public void send(){
		ArrayList<Information>list=new ArrayList<Information>();
		Information info;
		Set keySet = cm.getCache().getSubCache().keySet();
		Iterator keys = keySet.iterator();
		if(keys.hasNext())
		{
			info=(Information)keys.next();
			send(info);
			list.add(info);
		}
		removing(list);
		System.out.println("Informations sent..=====>");
	}

	void removing(ArrayList<Information>list){
		if(list.size() >0){
			for (int i = 0; i < list.size(); i++) {
				cm.getCache().getSubCache().remove(list.get(i));
			}
		}
	}
}
